package com.morningstar.common.utils.crypto;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;


/** 
 * AES安全编码组件
 * @author Lian Shan Yang
 */  
public class AESCrypto {

    /**
     *
     */
    private static final Logger logger = LoggerFactory.getLogger(AESCrypto.class);

    private static final String AES = "AES";

    /**
     * 加密 
     * @param content   加密的内容
     * @param key       秘钥
     * @return          加密后内容
     */
    public static String strEnc(String key,String content) {
        try {
            org.apache.commons.codec.binary.Base64 base64 = new org.apache.commons.codec.binary.Base64();
            KeyGenerator kgen = KeyGenerator.getInstance(AES);
            kgen.init(128, new SecureRandom(key.getBytes()));
            SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), AES);
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key_ = new SecretKeySpec(enCodeFormat, AES);
            Cipher cipher = Cipher.getInstance(AES);
            byte[] byteContent = content.getBytes(StandardCharsets.UTF_8);
            cipher.init(Cipher.ENCRYPT_MODE, key_);
            byte[] result = cipher.doFinal(byteContent);
            return base64.encodeAsString(result);
        } catch (Exception e) {
            logger.error(ExceptionUtils.getStackTrace(e));
            return null;
        }
    }

    /**
     * 解密 
     * @param data  待解密内容
     * @param key   秘钥
     * @return      解密后内容
     */
    public static String strDec(String key,String data) {
        try {
            org.apache.commons.codec.binary.Base64 base64 = new org.apache.commons.codec.binary.Base64();
            byte[] content = base64.decode(data);
            KeyGenerator kgen = KeyGenerator.getInstance(AES);
            kgen.init(128, new SecureRandom(key.getBytes()));
            SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), AES);
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key_ = new SecretKeySpec(enCodeFormat, AES);
            Cipher cipher = Cipher.getInstance(AES);
            cipher.init(Cipher.DECRYPT_MODE, key_);
            byte[] result = cipher.doFinal(content);
            return new String(result);
        } catch (Exception e) {
            logger.error(ExceptionUtils.getStackTrace(e));
            return null;
        }
    }

    /**
     * 测试
     * @param args
     */
    public static void main(String[] args) {
        String keypassword = "SNQ36AOYE597F48G";
        String str = "15040335739";
        String strEnc = strEnc(keypassword, str);
        System.out.println(strEnc);
        String strDeC = strDec(keypassword, "BgcyGiIqGKAlIXrRZqhCTw==");
        System.out.println(strDeC);
    }
}  
